<template>
  <Layout>
    <div class="file-management max-width-1500">
      <div class="header">
        <h2>文件管理</h2>
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文件名或类型"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchFileList"
            @keydown.enter="fetchFileList"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchFileList" />
            </template>
          </el-input>
          <el-button type="primary" @click="handleUploadClick">上传文件</el-button>
          <input 
            ref="fileInputRef" 
            type="file" 
            multiple 
            style="display: none;" 
            @change="handleFileSelect"
          />
          <el-button type="success" @click="fetchFileList" :loading="loading" style="margin-left: 10px;">
            刷新
          </el-button>
          <el-button
            type="danger"
            @click="handleBatchDelete"
            :disabled="selectedFiles.length === 0"
            style="margin-left: 10px;"
          >
            批量删除({{ selectedFiles.length }})
          </el-button>
        </div>
      </div>

      <FileUpload 
        ref="fileUploadRef"
        v-model="uploadDialogVisible"
        @upload-success="handleUploadSuccess"
      />

      <div class="table-container">
        <el-table
          :data="fileList"
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="upload_id" label="文件ID" width="100" sortable />
          <el-table-column label="缩略图" width="120">
            <template #default="scope">
              <div class="thumbnail-container" v-if="isImageFile(scope.row.mimetype)">
                <el-image
                  :src="scope.row.fileurl"
                  class="thumbnail"
                  fit="cover"
                  :preview-src-list="[scope.row.fileurl]"
                  preview-teleported
                />
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="文件名" show-overflow-tooltip sortable prop="original_name">
            <template #default="scope">
              <span>{{ scope.row.original_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="mimetype" label="文件类型" width="150" />
          <el-table-column prop="size" label="文件大小" width="120" sortable />
          <el-table-column label="上传用户" width="150">
            <template #default="scope">
              <span v-if="scope.row.upload_user">{{ scope.row.upload_user.name || scope.row.upload_user.account }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="上传时间" width="200" sortable />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                type="primary" 
                @click="handleDownload(scope.row)"
              >
                下载
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteFile(scope.row)"
                :loading="deletingFileId === scope.row.upload_id"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[50, 500, 1000]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Layout from '@/components/Layout.vue'
import FileUpload from '@/components/FileUpload.vue'
import type { UploadFile } from '@/api/modules/upload'
import { getUploadListPage, deleteUpload, batchDeleteUpload } from '@/api/modules/upload'
import { formatFileSize, isImageFile } from '@/utils'

// 文件列表
const fileList = ref<UploadFile[]>([])

// 加载状态
const loading = ref(false)

// 删除文件时的加载状态
const deletingFileId = ref<number | null>(null)

// 选中的文件
const selectedFiles = ref<UploadFile[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 排序字段
const sortField = ref('createdAt')

// 排序方式
const sortOrder = ref('DESC')

// 分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 上传相关
const fileInputRef = ref<HTMLInputElement | null>(null)
const uploadDialogVisible = ref(false)

// 上传组件引用
const fileUploadRef = ref<InstanceType<typeof FileUpload> | null>(null)

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string }) => {
  if (sort.prop) {
    sortField.value = sort.prop;
    sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC';
  } else {
    sortField.value = 'createdAt';
    sortOrder.value = 'DESC';
  }
  fetchFileList();
};

// 获取文件列表
const fetchFileList = async () => {
  loading.value = true
  try {
    const response = await getUploadListPage({
      page: pagination.value.page,
      limit: pagination.value.limit,
      keyword: searchKeyword.value || undefined,
      sort_field: sortField.value,
      sort_order: sortOrder.value
    })
    
    fileList.value = response.data?.list || []
    pagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    console.error('获取文件列表失败:', error)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchFileList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchFileList()
}

// 处理选择变化
const handleSelectionChange = (val: UploadFile[]) => {
  selectedFiles.value = val
}

// 处理上传按钮点击
const handleUploadClick = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    // 使用新的上传组件
    fileUploadRef.value?.setFiles(input.files)
    uploadDialogVisible.value = true
    // 清空input的value，以便下次选择相同文件时也能触发change事件
    input.value = ''
  }
}

// 处理上传完成
const handleUploadSuccess = async () => {
  // 上传完成后刷新文件列表
  await fetchFileList()
}

// 处理下载
const handleDownload = (file: UploadFile | null) => {
  if (file) {
    // 直接使用后端返回的完整URL
    const fullUrl = file.fileurl;
    
    // 创建一个临时的 a 标签
    const link = document.createElement('a');
    link.href = fullUrl;
    link.download = file.original_name;
    link.target = '_blank'; // 在新窗口打开
    link.rel = 'noopener noreferrer'; // 安全考虑
    
    // 临时添加到页面中
    document.body.appendChild(link);
    
    // 触发点击
    link.click();
    
    // 立即移除
    document.body.removeChild(link);
  }
}

// 处理删除文件
const handleDeleteFile = async (file: UploadFile) => {
  ElMessageBox.confirm(
    `确定要删除文件 "${file.original_name}" 吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!file.upload_id) return
    
    deletingFileId.value = file.upload_id
    try {
      await deleteUpload(file.upload_id)
      ElMessage.success('删除成功')
      // 重新获取文件列表
      fetchFileList()
    } catch (error) {
      console.error('删除文件失败:', error)
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    } finally {
      deletingFileId.value = null
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除文件
const handleBatchDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const fileIds = selectedFiles.value.map(file => file.upload_id!).filter(id => id !== undefined);
      if (fileIds.length === 0) {
        ElMessage.warning('请选择有效的文件进行删除');
        return;
      }
      
      await batchDeleteUpload(fileIds);
      ElMessage.success(`成功删除${fileIds.length}个文件`);
      // 清空选中项
      selectedFiles.value = [];
      // 重新获取文件列表
      await fetchFileList();
    } catch (error) {
      console.error('批量删除文件失败:', error);
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 组件挂载时获取文件列表
onMounted(() => {
  fetchFileList()
})
</script>

<style scoped>
.file-management {
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  height: calc(100% - 150px);
  overflow: auto;
}

.thumbnail-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
}

.thumbnail {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.upload-item {
  margin-bottom: 15px;
}

.upload-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.file-name {
  font-size: 14px;
  color: #606266;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

<!-- 添加全局样式来解决图片预览的层级问题 -->
<style>
.viewer-container {
  z-index: 9999 !important;
}

.viewer-mask {
  z-index: 9998 !important;
  background-color: rgba(0, 0, 0, 0.8) !important;
}

/* 预览时禁用表格交互 */
.viewer-open .el-table {
  pointer-events: none !important;
}

.viewer-open .el-table .el-image {
  pointer-events: auto !important;
}
</style>